// pages/login/login.js
import {
  reqLogin,
  reqUserInfo
} from '../../api/user'
import {
  toast
} from '../../utils/extendApi'
import {
  setStorage
} from '../../utils/storage'
// 导入ComponentWithStore方法
import {
  ComponentWithStore
} from 'mobx-miniprogram-bindings'
// 导入store对象
import {userStore} from '../../stores/userstore'
ComponentWithStore({
  storeBindings:{
    store:userStore,
    fields:['token','userInfo'],
    actions:['setToken','setUserInfon']
  },
  methods: {
    // 点击授权登录
    changeLogin() {
      wx.login({
        success: async ({
          code
        }) => {
          if (code) {
            // let res = await reqLogin(code)
            //json模拟后台不带code进行请求
            let res = await reqLogin()
            if (res.code == 200) {
              setStorage('token', res.data.token)
              this.setToken(res.data.token)
              // 获取用户信息
              this.getUserInfo()
              wx.navigateBack()
            } else {
              toast({
                title: res.message
              })
            }
          } else {
            toast({
              title: '登录失败，请从新登录'
            })
          }
        },
      })
    },
    //获取用户信息
    async getUserInfo(){
      let res = await reqUserInfo()
      if(res.code == 200){
        setStorage('userInfo', res.data)
        this.setUserInfon(res.data)
      }
    }
  }

})